using System;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace FileManager.Converters
{
    /// <summary>
    /// 将流转换为图像的转换器
    /// 用于处理微信加密图片和普通图片的预览显示
    /// </summary>
    public class StreamToImageConverter : IValueConverter
    {
        /// <summary>
        /// 将流转换为BitmapImage对象
        /// </summary>
        /// <param name="value">输入的流对象</param>
        /// <param name="targetType">目标类型</param>
        /// <param name="parameter">转换参数</param>
        /// <param name="culture">文化信息</param>
        /// <returns>转换后的BitmapImage对象，失败时返回null</returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Stream stream)
            {
                try
                {
                    // 保存当前流位置
                    long originalPosition = stream.Position;
                    
                    // 确保流可读取且有内容
                    if (stream.CanRead && stream.Length > 0)
                    {
                        // 创建新的内存流，避免原流关闭导致的问题
                        using (var memoryStream = new MemoryStream())
                        {
                            // 将原始流复制到内存流
                            stream.CopyTo(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            
                            var image = new BitmapImage();
                            image.BeginInit();
                            image.CacheOption = BitmapCacheOption.OnLoad;
                            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.IgnoreColorProfile;
                            image.StreamSource = memoryStream;
                            image.EndInit();
                            image.Freeze(); // 冻结图像以提高性能和线程安全性
                            
                            return image;
                        }
                    }
                    
                    // 恢复原始流位置
                    stream.Position = originalPosition;
                }
                catch (Exception ex)
                {
                    // 记录异常但不抛出，确保应用程序不会崩溃
                    Console.WriteLine($"StreamToImageConverter转换失败: {ex.Message}");
                }
                finally
                {
                    // 确保恢复流位置
                    if (stream != null && stream.CanSeek)
                    {
                        try { stream.Position = 0; }
                        catch { }
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 将图像转换回流（未实现）
        /// </summary>
        /// <param name="value">输入的图像对象</param>
        /// <param name="targetType">目标类型</param>
        /// <param name="parameter">转换参数</param>
        /// <param name="culture">文化信息</param>
        /// <returns>不实现，始终抛出NotImplementedException</returns>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}